package com.cenwangkeji.resident.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.cenwangkeji.resident.R;
import com.cenwangkeji.resident.model.Constant;
import com.cenwangkeji.resident.model.OkHttpUtils;
import com.cenwangkeji.resident.model.bean.BasicInfoBean;
import com.cenwangkeji.resident.model.bean.ImgBean;
import com.cenwangkeji.resident.model.bean.SuccessBean;
import com.cenwangkeji.resident.model.bean.User;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lws.basic.base.BaseActivity;
import com.lws.basic.persenter.ObserverOnNext;
import com.lws.basic.utils.common.GsonUtils;
import com.lws.basic.utils.common.MyLogger;
import com.lws.basic.utils.common.MyToast;
import com.lws.basic.utils.common.RxUtils;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

//个人基本信息
public class InfoDetailActivity extends BaseActivity {


    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_sex)
    TextView mTvSex;
    @BindView(R.id.tv_birth)
    TextView mTvBirth;
    @BindView(R.id.tv_id)
    TextView mTvId;
    @BindView(R.id.tv_work)
    TextView mTvWork;
    @BindView(R.id.tv_phone)
    TextView mTvPhone;
    @BindView(R.id.tv_type)
    TextView mTvType;
    @BindView(R.id.tv_nation)
    TextView mTvNation;
    @BindView(R.id.tv_hospital)
    TextView mTvHospital;
    @BindView(R.id.tv_doctor)
    TextView mTvDoctor;
    @BindView(R.id.iv_head)
    ImageView mIv;

    @Override
    public int setLayoutId() {
        return R.layout.activity_info_detail;
    }


    @Override
    public void initData() {
        super.initData();
        ButterKnife.bind(this);

        getUser();
    }

    @OnClick({R.id.iv_head,R.id.tv_detail})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.iv_head:
                openPhoto();
                 break;
            case R.id.tv_detail:
                startActivity(new Intent(this,InfoHealthDetailActivity.class));
                break;

        }

    }

    //打开相册
    public void openPhoto() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .minSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)
                .previewImage(true)
                .isCamera(true)
                .compress(true)
                .enableCrop(false)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    final List<LocalMedia> list = PictureSelector.obtainMultipleResult(data);
                    Glide.with(InfoDetailActivity.this).load(list.get(0).getCompressPath()).apply(new RequestOptions().circleCrop().error(R.mipmap.ic_user)).into(mIv);
                    Observable.create(new ObservableOnSubscribe<SuccessBean>() {
                        @Override
                        public void subscribe(ObservableEmitter<SuccessBean> emitter) throws Exception {
                            File file = new File(list.get(0).getCompressPath());
                            String json = OkHttpUtils.uploadImage(Constant.image_url,file);
                            MyLogger.i(json);
                            Gson gson = GsonUtils.getInstance();
                            ImgBean imgBean = gson.fromJson(json, ImgBean.class);
                            Map<Object,Object> map = new HashMap<>();
                            map.put( Constant.token, User.getToken());
                            map.put( "mark",3);
                            map.put("userId", User.getUserId());
                            map.put("picId", imgBean.getFileUrl().get(0));
                            JSONObject jsonObject = new JSONObject(map);
                            MyLogger.i(jsonObject.toString());
                            json = OkHttpUtils.post(jsonObject.toString(), Constant.image_updata);
                            SuccessBean successBean  = gson.fromJson(json, SuccessBean.class);
                            emitter.onNext(successBean);


                        }
                    }).compose(RxUtils.<SuccessBean>io_main()).subscribe(new ObserverOnNext<SuccessBean>() {
                        @Override
                        public void onNext(SuccessBean bean) {
                            if (bean.getMsg().equals(Constant.token_expired)){
                                signIn();
                            }else {
                                if (bean.getCode() ==0){
                                   MyToast.show("更换头像成功");
                                }else {
                                    MyToast.show(bean.getMsg());
                                }
                            }
                        }
                    });

            }
        }
    }



    //获取用户信息
    private void getUser(){
        showLoading();
        Observable.create(new ObservableOnSubscribe<BasicInfoBean>() {
            @Override
            public void subscribe(ObservableEmitter<BasicInfoBean> emitter) throws Exception {
                Map<Object,Object> map = new HashMap<>();
                map.put( Constant.token, User.getToken());
                map.put( "mark",3);
                map.put("userId", User.getUserId());
                JSONObject jsonObject = new JSONObject(map);
                MyLogger.i(jsonObject.toString());
                String json = OkHttpUtils.post(jsonObject.toString(), Constant.user_detail);
                MyLogger.i(json);
                Gson gson = GsonUtils.getInstance();
                emitter.onNext(gson.fromJson(json, BasicInfoBean.class ));
            }
        }).compose(RxUtils.<BasicInfoBean>io_main()).subscribe(new ObserverOnNext<BasicInfoBean>() {
            @Override
            public void onNext(BasicInfoBean bean) {
                if (bean.getMsg().equals(Constant.token_expired)){
                    signIn();
                }else {
                    if (bean.getData() != null){
                        mTvName.setText(bean.getData().getXm());
                        if (bean.getData().getXb()==1){
                            mTvSex.setText("男");
                        }else {
                            mTvSex.setText("女");
                        }
                        Glide.with(InfoDetailActivity.this).load(Constant.base+bean.getData().getPicUrl()).apply(new RequestOptions().error(R.mipmap.ic_user).circleCrop()).into(mIv);
                        mTvId.setText(bean.getData().getSfzh());
                        mTvBirth.setText(bean.getData().getCsrq().substring(0, 11));
                        if (TextUtils.isEmpty(bean.getData().getGzdw())){
                            mTvWork.setText("无");
                        }else {
                            mTvWork.setText(bean.getData().getGzdw());

                        }
                        mTvPhone.setText(bean.getData().getPhone());
                        if (bean.getData().getCzlx() ==1){
                            mTvType.setText("户籍");
                        }else {
                            mTvType.setText("非户籍");
                        }
                        mTvNation.setText("汉族");
                        mTvHospital.setText(bean.getData().getYymc());
                        mTvDoctor.setText(bean.getData().getName());
                        mTvNation.setText(User.getNation(bean.getData().getMz()));

                    }else {
                        MyToast.show(bean.getMsg());
                    }

                }
                dismissLoading();


            }
        });
    }

}
